var imageResource;
var imageResourceOverlay;
var scaleX = 600;
var scaleY = 338;
var lastEvent;;

function createTextOverlay(string) {
    // Create a canvas to draw on
    var canvas = document.createElement('canvas');
    canvas.setAttribute('width', scaleX);
    canvas.setAttribute('height', scaleY);

    var context = canvas.getContext('2d');

    // Draw background
    context.fillStyle = '#BBB';
    context.fillRect(0,0,166,50);

    // Draw text
    context.font = '32pt Impact';
    context.lineWidth = 6;
    context.lineStyle = '#000';
    context.fillStyle = '#FFF';
    context.fillColor = '#ffff00';
    context.fillColor = '#ffff00';
    context.textAlign = 'center';
    context.textBaseline = 'bottom';
    context.strokeText(string, canvas.width / 2, canvas.height / 2);
    context.fillText(string, canvas.width / 2, canvas.height / 2);

    return canvas.toDataURL();
};

function createFaceOverlay(event) {
    var canvas = document.createElement('canvas');
    canvas.setAttribute('width', scaleX);
    canvas.setAttribute('height', scaleY);

    var context = canvas.getContext('2d');
    context.setTransform(1,0,0,1,0,0);
    context.translate(scaleX/2,scaleY/2);

    context.lineWidth = 6;
    context.strokeStyle = '#f00';
    context.fillStyle = '#FFF';
    context.fillColor = '#ffff00';
    context.fillColor = '#ffff00';

    // context.beginPath();
    // x = scaleX/2;
    // y = scaleY/2;
    // context.moveTo(-x, -y);
    // context.lineTo(-x, y);
    // context.lineTo(x, y);
    // context.lineTo(x, -y);
    // context.closePath();
    // context.stroke();

    context.beginPath();
    context.arc(scaleX * event.leftEye.x,
            scaleY * event.leftEye.y, 5, 0, 2*Math.PI);
    context.stroke();

    context.beginPath();
    context.arc(scaleX * event.rightEye.x,
            scaleY * event.rightEye.y, 5, 0, 2*Math.PI);
    context.stroke();

    context.strokeStyle = '#fff';

    context.beginPath();
    context.moveTo(scaleX * event.mouthLeft.x,
            scaleY * event.mouthLeft.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.upperLip.x,
            scaleY * event.upperLip.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.mouthRight.x,
            scaleY * event.mouthRight.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.lowerLip.x,
            scaleY * event.lowerLip.y, 5, 0, 2*Math.PI);
    context.closePath();
    context.stroke();

    context.beginPath();
    context.moveTo(scaleX * event.noseRoot.x,
            scaleY * event.noseRoot.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.noseTip.x,
            scaleY * event.noseTip.y, 5, 0, 2*Math.PI);
    context.stroke();

    context.beginPath();
    context.moveTo(scaleX * event.leftEyebrowLeft.x,
            scaleY * event.leftEyebrowLeft.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.leftEyebrowRight.x,
            scaleY * event.leftEyebrowRight.y, 5, 0, 2*Math.PI);
    context.stroke();

    context.beginPath();
    context.moveTo(scaleX * event.rightEyebrowLeft.x,
            scaleY * event.rightEyebrowLeft.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.rightEyebrowRight.x,
            scaleY * event.rightEyebrowRight.y, 5, 0, 2*Math.PI);
    context.stroke();

    // context.beginPath();
    // context.arc(scaleX * event.mouthCenter.x,
    //         scaleY * event.mouthCenter.y, 5, 0, 2*Math.PI);
    // context.stroke();
    // context.arc(0,
    //         0, 5, 0, 2*Math.PI);
    return canvas.toDataURL();

};

function updateOverlay() {
    var newResource = gapi.hangout.av.effects.createImageResource(
            createFaceOverlay(lastEvent));

    // var newResourceOverlay = newResource.createFaceTrackingOverlay({
    //         'trackingFeature':
    //         gapi.hangout.av.effects.FaceTrackingFeature.NOSE_TOP,
    //         'scaleWithFace': true,
    //         'rotateWithFace': true,
    //         'scale': 2.0
    // });
    var newResourceOverlay = newResource.createOverlay({
            'scale': {
                'magnitude': 1,
                'reference':
                gapi.hangout.av.effects.ScaleReference.WIDTH
            }
    });
    // Put the text x-centered and near the bottom of the frame
    // newResourceOverlay.setPosition(0.5, 0);
    newResourceOverlay.setVisible(true);
    if (imageResource && imageResourceOverlay) {
        imageResourceOverlay.dispose();
        imageResource.dispose();
    }

    imageResource = newResource;
    imageResourceOverlay = newResourceOverlay;
};

function animationLoop() {
    window.setTimeout(animationLoop, 100);
    if (!lastEvent) {
        return;
    }
    updateOverlay();
};

function onFaceTrackingChanged(event) {
    try {
        if (event.hasFace) {
            lastEvent = event;
            updateOverlay();
        }
    } catch(e) {
        console.log("onFaceTrackingChanged: ERROR");
        console.log(e);
    }
};

function handleMirrorChange(obj) {
    window.console.log('Checked: ' + obj.target.checked);
    window.console.log(obj);
    gapi.hangout.av.setLocalParticipantVideoMirrored(obj.target.checked);
};

function init(eventObj) {
    if (eventObj.isApiReady) {
        gapi.hangout.av.setLocalParticipantVideoMirrored(false);
        var mirrorCheckbox = document.getElementById('mirrorVideo');
        mirrorCheckbox.checked =
                gapi.hangout.av.isLocalParticipantVideoMirrored();
        mirrorCheckbox.onchange = handleMirrorChange;

        window.console.log("initialized");
        // Add event handler.
        gapi.hangout.av.effects.onFaceTrackingDataChanged.
                add(onFaceTrackingChanged);
        // animationLoop();
        // var fancy = gapi.hangout.av.effects.createImageResource(
        //         createTextOverlay('Foo Bar!'));
        // Create this non-moving overlay that will be 100% of the width
        // of the video feed.
        // fancyOverlay = fancy.createOverlay(
        //         {'scale': {
        //             'magnitude': 0.5,
        //             'reference': gapi.hangout.av.effects.ScaleReference.WIDTH
        //         }});
        // // Put the text x-centered and near the bottom of the frame
        // fancyOverlay.setPosition(0.5, 0);
        // fancyOverlay.setVisible(true);
        // minScale['fancy'] = 1.0;
        // maxScale['fancy'] = 2.5;
    }
};

// Wait for gadget to load.
gadgets.util.registerOnLoadHandler(function() {
    gapi.hangout.onApiReady.add(init);
});
